package com.frank.oj.service.entity.group.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frank.model.entity.training.Training;
import com.frank.model.entity.training.TrainingProblem;
import com.frank.oj.mapper.GroupTrainingMapper;
import com.frank.oj.model.vo.TrainingVO;
import com.frank.oj.service.entity.group.GroupTrainingEntityService;
import com.frank.oj.service.entity.training.TrainingProblemEntityService;
import com.frank.oj.shiro.AccountProfile;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.RegEx;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author frank
 * @Date 2024/5/4
 */
@Service
public class GroupTrainingEntityServiceImpl extends ServiceImpl<GroupTrainingMapper, Training> implements GroupTrainingEntityService {
    @Resource
    private GroupTrainingMapper groupTrainingMapper;
    @Resource
    private TrainingProblemEntityService trainingProblemEntityService;
    @Override
    public IPage<TrainingVO> getTrainingList(Integer limit, Integer currentPage, Long gid) {
        IPage<TrainingVO> iPage = new Page<>(currentPage, limit);

        List<TrainingVO> trainingList = groupTrainingMapper.getTrainingList(iPage, gid);

        // 当前用户有登录，且训练列表不为空，则查询用户对于每个训练的做题进度
        if (!trainingList.isEmpty()) {
            AccountProfile userRole = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

            List<Long> tidList = trainingList.stream().map(TrainingVO::getId).collect(Collectors.toList());
            List<TrainingProblem> trainingProblemList = trainingProblemEntityService.getGroupTrainingListAcceptedCountByUid(tidList, gid, userRole.getUid());

            HashMap<Long, Integer> tidMapCount = new HashMap<>(trainingList.size());
            for (TrainingProblem trainingProblem : trainingProblemList) {
                int count = tidMapCount.getOrDefault(trainingProblem.getTid(), 0);
                count++;
                tidMapCount.put(trainingProblem.getTid(), count);
            }

            for (TrainingVO trainingVo : trainingList) {
                Integer count = tidMapCount.getOrDefault(trainingVo.getId(), 0);
                trainingVo.setAcCount(count);
            }
        }

        return iPage.setRecords(trainingList);
    }

    @Override
    public IPage<Training> getAdminTrainingList(Integer limit, Integer currentPage, Long gid) {
        IPage<Training> iPage = new Page<>(currentPage, limit);
        List<Training> trainingList = groupTrainingMapper.getAdminTrainingList(iPage, gid);

        return iPage.setRecords(trainingList);
    }
}
